package com.strive.user.controller;

import cn.hutool.core.convert.Convert;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.strive.common.constant.CommonConstant;
import com.strive.common.model.base.PageResult;
import com.strive.common.model.base.Result;
import com.strive.common.model.dto.SysMenu;
import com.strive.common.model.dto.SysPower;
import com.strive.user.service.ISysMenuService;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/2/22 14:20
 * @Version 1.0
 */
@RestController
@Api(tags = "菜单模块api")
@Slf4j
@RequestMapping("/menus")
public class SysMenuController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 删除菜单
     *
     * @param id
     */
    @ApiOperation(value = "删除菜单")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        try {
            menuService.deleteMenusPowers(id);
            return Result.succeed("操作成功");
        } catch (Exception ex) {
            log.error("memu-delete-error", ex);
            return Result.failed("操作失败");
        }
    }

    /**
     *
     * @param roleId
     * @return
     */
    @ApiOperation(value = "根据roleId获取对应的菜单")
    @GetMapping("/{roleId}/menus")
    public Result<List<SysMenu>> findMenusByRoleId(@PathVariable String roleId) {
        //获取该角色对应的菜单
        Set<String> roleIds = (Set<String>) Convert.toCollection(HashSet.class, String.class, roleId);
        if(CollectionUtils.isEmpty(roleIds)){
            return Result.succeed(Lists.newArrayList());
        }

        //转换一下数据兼容接口
        Set<Long> roleSets = new HashSet<>();
        for (String id : roleIds) {
            roleSets.add(Long.parseLong(id));
        }
        List<SysMenu> roleMenus = menuService.findByRoles(roleSets,null);
        return Result.succeed(roleMenus);
    }

    @ApiOperation(value = "根据roleCodes获取对应的权限")
    @SuppressWarnings("unchecked")
//    @Cacheable(value = "menu", key ="#roleCodes")
    @GetMapping("/{roleCodes}")
    public Result<List<SysPower>> findPowersByRoles(@PathVariable String roleCodes) {
        List<SysPower> result = null;
        if (StringUtils.isNotEmpty(roleCodes)) {
            Set<String> roleSet = (Set<String>) Convert.toCollection(HashSet.class, String.class, roleCodes);
            result = menuService.findPowersByRoles(roleSet);

        }
        return Result.succeed(result);
    }

    /**
     * 给角色分配菜单
     */
    @ApiOperation(value = "角色分配菜单")
    @PostMapping("/granted")
    public Result setMenuToRole(@RequestBody SysMenu sysMenu) {
        menuService.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
        return Result.succeed("操作成功");
    }

    /**
     * 查询所有菜单
     * @return
     */
    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/findAlls")
    public PageResult<SysMenu> findAlls() {
        List<SysMenu> list = menuService.findAll();
        return PageResult.<SysMenu>builder().data(list).status(200).count((long) list.size()).build();
    }


    /**
     * 查询所有菜单
     * @return
     */
    @ApiOperation(value = "查询所有菜单和权限")
    @GetMapping("/findAllMenusAndPowers")
    public PageResult<SysMenu> findAllMenusAndPowers() {
        List<SysMenu> list = menuService.findAll();
        return PageResult.<SysMenu>builder().data(list).status(200).count((long) list.size()).build();
    }

    /**


    /**
     * 获取菜单以及顶级菜单
     * @return
     */
    @ApiOperation(value = "获取菜单以及顶级菜单")
    @GetMapping("/findOnes")
    public PageResult<SysMenu> findOnes() {
        List<SysMenu> list = menuService.findOnes();
        return PageResult.<SysMenu>builder().data(list).status(200).count((long) list.size()).build();
    }

    /**
     * 添加菜单 或者 更新
     *
     * @param menu
     * @return
     */
    @ApiOperation(value = "新增菜单")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody SysMenu menu) {
        try {
            menuService.saveOrUpdate(menu);
        } catch (Exception ex) {
            log.error("memu-saveOrUpdate-error", ex);
            return Result.failed("操作失败");
        }
        return Result.succeed("操作成功");
    }

    /**
     * 当前登录用户的菜单
     *
     * @return
     */
    @PostMapping("/current/{roleCodes}")
    @ApiOperation(value = "查询当前用户菜单")
    public Result<List<SysMenu>> findMyMenuAndPowers(@PathVariable String roleCodes) {
        if (StringUtils.isEmpty(roleCodes)) {
            return Result.succeed(Collections.emptyList());
        }
        Set<String> roleSet = (Set<String>) Convert.toCollection(HashSet.class, String.class, roleCodes);
        List<SysMenu> menusList = menuService.findMyMenuAndPowers(roleSet);
        return Result.succeed(menusList);
    }

    /**
     * 两层循环实现建树
     *
     * @param sysMenus
     * @return
     */
    public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
        List<SysMenu> menus = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            if (Objects.isNull(sysMenu.getParent())) {
                menus.add(sysMenu);
            }
            for (SysMenu menu : sysMenus) {
                if (menu.getParent().equals(sysMenu.getId())) {
                    if (sysMenu.getSubMenus() == null) {
                        sysMenu.setSubMenus(new ArrayList<>());
                    }
                    sysMenu.getSubMenus().add(menu);
                }
            }
        }
        return menus;
    }

}
